package com.guli.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guli.common.utils.Constant;
import com.guli.common.utils.PageUtils;
import com.guli.product.dao.*;
import com.guli.product.entity.AttrAttrgroupRelationEntity;
import com.guli.product.entity.AttrEntity;
import com.guli.product.entity.AttrGroupEntity;
import com.guli.product.entity.CategoryEntity;
import com.guli.product.service.AttrGroupService;
import com.guli.product.vo.AttrGroupWithAttrVo;
import com.guli.product.vo.AttrVo;
import com.guli.product.vo.SpuItemAttrGroupVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;


@Service("attrGroupService")
public class AttrGroupServiceImpl extends ServiceImpl<AttrGroupDao, AttrGroupEntity> implements AttrGroupService {

    @Autowired
    private CategoryDao categoryDao;
    @Autowired
    private AttrAttrgroupRelationDao attrAttrgroupRelationDao;
    @Autowired
    private AttrGroupDao attrGroupDao;
    @Autowired
    private AttrDao attrDao;

    @Override
    public PageUtils queryPage(Long catId, Map<String, Object> params) {
        Page<AttrGroupEntity> pages = baseMapper.selectPage
                (new Page<>(Long.parseLong((String) params.get(Constant.PAGE)), Long.parseLong((String) params.get(Constant.LIMIT))),
                        new QueryWrapper<AttrGroupEntity>().eq(catId != 0, "category_id", catId)
                                .like(!StringUtils.isEmpty(params.get(Constant.KEY)), "attr_group_name", params.get(Constant.KEY))
                                .orderByAsc("sort"));
        List<AttrGroupEntity> list = pages.getRecords();
        if (!CollectionUtils.isEmpty(list)) {
            if (catId == 0) {
                list.forEach(attrGroup -> {
                    Long categoryId = attrGroup.getCategoryId();
                    CategoryEntity category = categoryDao.selectById(categoryId);
                    String categoryName = category.getName();
                    attrGroup.setCategoryName(categoryName);
                });
            } else {
                CategoryEntity category = categoryDao.selectById(catId);
                String categoryName = category.getName();
                list.forEach(attrGroup -> attrGroup.setCategoryName(categoryName));
            }
        }
        return new PageUtils(pages);
    }

    @Override
    public AttrGroupEntity getInfoById(Long attrGroupId) {
        AttrGroupEntity attrGroup = baseMapper.selectById(attrGroupId);
        //获取该属性分组对应的分类ID
        Long catelogId = attrGroup.getCategoryId();
        CategoryEntity categoryEntity = categoryDao.selectById(catelogId);
        if (categoryEntity == null) {
            return attrGroup;
        }
        Long[] categoryPath = getCategoryPath(catelogId, categoryEntity);
        attrGroup.setCategoryPath(categoryPath);
        return attrGroup;
    }

    @Override
    public Long[] getCategoryPath(Long catelogId, CategoryEntity categoryEntity) {
        //获取多层分类信息
        List<Long> catelogPath = new ArrayList<>();
        catelogPath.add(catelogId);
        Long parentCid = categoryEntity.getParentCid();
        while (parentCid != 0) {
            catelogPath.add(parentCid);
            categoryEntity = categoryDao.selectById(parentCid);
            parentCid = categoryEntity.getParentCid();
        }
        Collections.reverse(catelogPath);
        return catelogPath.toArray(new Long[0]);
    }

    @Override
    public void removeGroupIdsAndRelation(List<Long> ids) {
        baseMapper.deleteBatchIds(ids);
        attrAttrgroupRelationDao.updateAttrGroupId(ids);
    }

    @Override
    public List<AttrGroupWithAttrVo> catagoryWithAttr(Long catId) {
        //查询catId对应的分类
        CategoryEntity category = categoryDao.selectById(catId);
        //获取分类名称
        String categoryName = category.getName();
        //根据catId获取当前分类下的所有属性分组
        List<AttrGroupEntity> attrGroupList = attrGroupDao
                .selectList(new QueryWrapper<AttrGroupEntity>().eq("category_id", catId));
        List<AttrGroupWithAttrVo> AttrGroupWithAttrVos = null;
        if (!CollectionUtils.isEmpty(attrGroupList)) {
            //查询所有关联的属性
            AttrGroupWithAttrVos = attrGroupList.stream().map(attrGroup -> {
                AttrGroupWithAttrVo attrGroupWithAttrVo = new AttrGroupWithAttrVo();
                BeanUtils.copyProperties(attrGroup, attrGroupWithAttrVo);
                //获取分组Id
                Long attrGroupId = attrGroup.getAttrGroupId();
                //获取关联该属性分组的所有属性
                List<AttrAttrgroupRelationEntity> attrgroupRelations = attrAttrgroupRelationDao
                        .selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", attrGroupId));
                if (!CollectionUtils.isEmpty(attrgroupRelations)) {
                    List<Long> attrIds = attrgroupRelations
                            .stream().map(AttrAttrgroupRelationEntity::getAttrId).collect(Collectors.toList());
                    List<AttrEntity> attrList = attrDao.selectBatchIds(attrIds);
                    List<AttrVo> attrVos = attrList.stream().map(attr -> {
                        AttrVo attrVo = new AttrVo();
                        BeanUtils.copyProperties(attr, attrVo);
                        attrVo.setCategoryName(categoryName);
                        return attrVo;
                    }).collect(Collectors.toList());
                    attrGroupWithAttrVo.setAttrs(attrVos);
                } else {
                    attrGroupWithAttrVo.setAttrs(Collections.emptyList());
                }
                return attrGroupWithAttrVo;
            }).collect(Collectors.toList());
        }
        return AttrGroupWithAttrVos;
    }

    @Override
    public List<SpuItemAttrGroupVo> getAttrGroupWithAttrsBySpuId(Long spuId, Long catalogId) {
        List<SpuItemAttrGroupVo> withAttrsBySpuId = baseMapper.getAttrGroupWithAttrsBySpuId(spuId, catalogId);
        return withAttrsBySpuId;
    }
}